package com.bite.java_chatroom.controller;

import com.bite.java_chatroom.component.OnlineUserManager;
import com.bite.java_chatroom.mapper.FriendMapper;
import com.bite.java_chatroom.mapper.MessageMapper;
import com.bite.java_chatroom.mapper.MessageSessionMapper;
import com.bite.java_chatroom.model.MessageReq;
import com.bite.java_chatroom.model.MessageResp;
import com.bite.java_chatroom.model.UserInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class WebSocketController extends TextWebSocketHandler {
    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private OnlineUserManager onlineUser;
    @Autowired
    private FriendMapper friendMapper;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private OnlineUserManager userManager;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("[WebSocket]连接成功！");
        UserInfo userInfo = (UserInfo) session.getAttributes().get("session_user_info");
        if(userInfo == null){
            return;
        }
        userManager.online(userInfo.getId(),session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        UserInfo userInfo = (UserInfo) session.getAttributes().get("session_user_info");
        if(userInfo == null){
            log.info("用户未登录,无法转发消息");
            return;
        }
        MessageReq req = objectMapper.readValue(message.getPayload(),MessageReq.class);
        if(req.getType().equals("message")){
            log.info(req.toString());
            SendMessage(userInfo,req);
        }else if(req.getType().equals("addFriend")){
            SendAddRequest(userInfo,req);
        }else {
            log.warn("req.type有误"+message.getPayload());
            return;
        }
    }

    private void SendAddRequest(UserInfo userInfo, MessageReq req) throws IOException {
        //构造转发消息
        MessageResp resp = new MessageResp();
        resp.setType("addFriend");
        resp.setFromName(userInfo.getUsername());
        resp.setFromId(userInfo.getId());
        resp.setContent(req.getContent());

        WebSocketSession session = onlineUser.getSession(req.getFriendId());
        if(session != null){
            log.info(userInfo.getUsername()+"向"+req.getFriendId()+"发送好友申请");
            String respJson = objectMapper.writeValueAsString(resp);
            session.sendMessage(new TextMessage(respJson));
            friendMapper.addFriendInvite(userInfo.getId(),userInfo.getUsername(),req.getFriendId(),req.getContent());
        }else {
            friendMapper.addFriendInviteNoOnline(userInfo.getId(),userInfo.getUsername(),req.getFriendId(),req.getContent());
        }
    }

    private void SendMessage(UserInfo userInfo, MessageReq req) throws IOException {
        //构造转发消息
        MessageResp resp = new MessageResp();
        resp.setType("message");
        resp.setContent(req.getContent());
        resp.setFromId(userInfo.getId());
        resp.setFromName(userInfo.getUsername());
        resp.setSessionId(req.getSessionId());
        String respJson = objectMapper.writeValueAsString(resp);

        //获取转发消息对象
        List<UserInfo> friends = messageSessionMapper.getFriendsBySessionId(req.getSessionId());
        //System.out.println(friends.toString());
        for(UserInfo friend : friends){
            WebSocketSession session = onlineUser.getSession(friend.getId());
            if(session == null){
                System.out.println("用户["+friend.getUsername()+"]不在线");
                //用户不在线
                continue;
            }
            log.info(userInfo.getUsername()+"对"+friend.getUsername()+"说:"+resp.getContent());
            session.sendMessage(new TextMessage(respJson));
        }
        log.info("获取sessionId:"+req.toString());
        //将消息添加导数据库
        messageMapper.addMessage(userInfo.getId(),req.getSessionId(),req.getContent());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("[WebSocket]连接异常，断开!");

        UserInfo userInfo = (UserInfo) session.getAttributes().get("session_user_info");
        if(userInfo == null){
            return;
        }
        friendMapper.setAddFriendState(userInfo.getId());
        userManager.offline(userInfo.getId(),session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("[WebSocket]连接断开！");

        UserInfo userInfo = (UserInfo) session.getAttributes().get("session_user_info");
        if(userInfo == null){
            return;
        }
        friendMapper.setAddFriendState(userInfo.getId());
        userManager.offline(userInfo.getId(),session);
    }
}
